package com.jiayou.session

import com.jiayou.AuthenticatePackage
import com.jiayou.DefaultProtocolImpl
import com.jiayou.emnu.FrameType
import com.jiayou.tool.objectToByteArray
import io.ktor.network.sockets.*
import io.ktor.utils.io.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.Serializable

/**
@author lishuang
@data   2021-05-02  11:14
@info   字节类型传输
 */
class ByteClientSocketSession<T1 : Serializable, T2 : Serializable>(
    override var authenticatePackage: AuthenticatePackage<ByteArray, T1, T2>? = null
) :
    ClientSocketSession<ByteArray, T1, T2> {
    companion object {
        val logger: Logger = LoggerFactory.getLogger(DefaultServerSocketSession::class.java)
    }

    override fun onError(socket: Socket) = socket.close()

    override suspend fun onWaitClosed(socket: Socket) = socket.awaitClosed()

    //在打开连接时第一时间发送自己的身份信息
    override suspend fun onOpen(socket: Socket, output: ByteWriteChannel, input: ByteReadChannel) {
        val objectToByteArray = objectToByteArray(DefaultProtocolImpl(FrameType.Auth, authenticatePackage))
        output.writeInt(objectToByteArray.size)
        output.writeFully(objectToByteArray)
    }

}